package com.vitogiovanni.tobook;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.vitogiovanni.tobook.entity.localeendpoint.Localeendpoint;
import com.vitogiovanni.tobook.entity.localeendpoint.model.Locale;
import com.vitogiovanni.tobook.entity.localeendpoint.model.LocaleCollection;
import com.vitogiovanni.tobook.utilities.LocaleTaskCompleteListener;
import com.vitogiovanni.tobook.utilities.NetworkChecker;

public class PreferitiActivity extends BaseActivity implements LocaleTaskCompleteListener<List<Locale>>{
	
	private ProgressDialog progressDialog;
	private Fragment fragmentListaLocali;
	private LocaleTask localeTask;
	private Toast toast;
	
	private LocationManager myLocationManager;
	private LocationListener myLocationListener;
	private Location location;
	
	@Override
	protected void onStop()
	{
		super.onStop();
		if(localeTask != null)
		{
			localeTask.cancel(true);
		}
		if(toast != null)
		{
			toast.cancel();
		}
		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (!NetworkChecker.isInternetAvailable(PreferitiActivity.this)) {
			NetworkChecker.noConnectionToast(PreferitiActivity.this);
			return;
		}
		setContentView(R.layout.activity_preferiti);
		
		Intent intent = getIntent();
		String email = intent.getStringExtra(MainActivity.EMAIL_UTENTE);
		localeTask = (LocaleTask) new LocaleTask(this, this).execute(email);
		progressDialog = ProgressDialog.show(
				PreferitiActivity.this, "", "Caricamento in corso",
				true, true, new OnCancelListener() {
					public void onCancel(DialogInterface dialog) {
						
					}
				});
		progressDialog.setCanceledOnTouchOutside(false);
	}
	/*
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.preferiti, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		super.onOptionsItemSelected(item);
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	*/
	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_lista_locali,
					container, false);
			return rootView;
		}
	}
	
	@Override
	public void onTaskComplete(List<Locale> result) {
		if (progressDialog != null) 
		{
			progressDialog.dismiss();
		}
		FragmentManager fragManager = getFragmentManager();
		if(fragmentListaLocali == null){
			fragmentListaLocali = fragManager.findFragmentById(R.id.listaLocaliPreferiti);
		}
		if(result != null && result.size() > 0)
		{
			int i = 0;
			String[] distanzaLocale = new String[result.size()];
			location = getLocation();
			for (Locale loc : result) {
				Location locationDest = new Location("dest");
				locationDest.setLatitude(loc.getCoordinataY());
				locationDest.setLongitude(loc.getCoordinataX());
				if(location!=null)
				{
					float distance = location.distanceTo(locationDest)/1000;
					distanzaLocale[i] = String.format("%.2f", distance).replace(",", ".");
				}
				else
				{
					distanzaLocale[i] = "--";
				}
				i++;
			}
			((ListaLocaliFragment)fragmentListaLocali).updateListaLocali(result, distanzaLocale);
		}
		else{
			Context context = getApplicationContext();
			CharSequence text = getString(R.string.no_locali_preferiti);
			int duration = Toast.LENGTH_SHORT;

			toast = Toast.makeText(context, text, duration);
			toast.show();
		}

	}
	
	private Location getLocation()
	{
		String provider;
		Location location;
		myLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        
		myLocationListener = new LocationListener() {
        	
			@Override
        	public void onLocationChanged(Location location) {
				/*if(location!=null){
			        CameraPosition cameraPosition = new CameraPosition(new LatLng(location.getLatitude(), location.getLongitude()), 16, 0, 0);
			        map.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
		        }*/
        	}

			@Override
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
			}

			@Override
			public void onProviderEnabled(String provider) {
			}

			@Override
			public void onProviderDisabled(String provider) {
			}
        };

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAccuracy(Criteria.POWER_LOW);
        
        provider = myLocationManager.getBestProvider(criteria, true);
        
        location = getMyPosition(provider);
        return location;
	}
	
	private Location getMyPosition(String prov){
		try {
	        // getting GPS status
	        boolean isGPSEnabled = myLocationManager.isProviderEnabled(prov);

	        // getting network status
	        boolean isNetworkEnabled = myLocationManager.isProviderEnabled(prov);

	        if (!isGPSEnabled && !isNetworkEnabled) {
	            // no network provider is enabled
	        }
	        else {
	            if (isNetworkEnabled) {
	            	myLocationManager.requestLocationUpdates(prov, 1000, 0, myLocationListener);
	                if (myLocationManager != null) {
	                    location = myLocationManager.getLastKnownLocation(prov);
	                    /*if (location != null) {
	                        latitude = location.getLatitude();
	                        longitude = location.getLongitude();
	                    }*/
	                }
	            }
	            // if GPS Enabled get lat/long using GPS Services
	            if (isGPSEnabled) {
	                if (location == null) {
	                	myLocationManager.requestLocationUpdates(prov, 1000, 0, myLocationListener);
	                    if (myLocationManager != null) {
	                        location = myLocationManager.getLastKnownLocation(prov);
	                        /*if (location != null) {
	                            latitude = location.getLatitude();
	                            longitude = location.getLongitude();
	                        }*/
	                    }
	                }
	            }
	        }

	    } catch (Exception e) {
	        e.printStackTrace();
	    }

	    return location;
	}
	
	private class LocaleTask extends AsyncTask<String, Void, List<Locale>>
	{
		private LocaleTaskCompleteListener<List<Locale>> callback;
		
		public LocaleTask(Context context, LocaleTaskCompleteListener<List<Locale>> cb)
		{
			this.callback = cb;
		}
		
		@Override
		protected List<Locale> doInBackground(String... arg0) {
			
			Localeendpoint.Builder builder1 = new Localeendpoint.Builder(
					AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
					null);
			builder1 = CloudEndpointUtils.updateBuilder(builder1);
			builder1.setApplicationName("to-book");
			Localeendpoint localeEndpoint = builder1.build();
			List<Locale> locali = new ArrayList<Locale>();
			List<Locale> localiTemp = new ArrayList<Locale>();
			String emailUtente = arg0[0];
			
			try{
				LocaleCollection localiColl = localeEndpoint.findPreferitiUtente(emailUtente).execute();
				localiTemp = localiColl.getItems();
			}catch(IOException e){
				e.printStackTrace();
			}

			if(localiTemp != null)
			{
				for(Locale loc: localiTemp)
					{
						locali.add(loc);
					}
			}
			return locali;
			
		}
		
		@Override
		protected void onPostExecute(List<Locale> result) {
			
			if (progressDialog != null) 
			{
				progressDialog.dismiss();
			}
			callback.onTaskComplete(result);

		}
		
	}
	
	@Override
	public void onBackPressed(){
		super.onBackPressed();
		
		Intent homeIntent = new Intent(PreferitiActivity.this, MainActivity.class);
		homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(homeIntent);
	}

	

}
